import { HomeLink } from '@/types/home';
import { createResource } from 'solid-js';
import { getHomeLinks, getHomeLists, getListApps } from '@/lib/api/home';

const fetchLists = async () => {
  try {
    // 获取首页列表
    const homeLists = await getHomeLists();
    
    // 如果没有列表数据，返回空数组
    if (!homeLists || homeLists.length === 0) {
      return [];
    }

    // 获取所有列表的应用数据
    const listsWithApps = await Promise.all(
      homeLists.map(async (list) => {
        const apps = await getListApps(list.jsonUrl);
        return {
          title: list.name,
          apps
        };
      })
    );
    
    return listsWithApps;
  } catch (error) {
    console.error('获取应用列表失败:', error);
    return [];
  }
};

const getCarouselSlides = async (): Promise<HomeLink[]> => {
  return await getHomeLinks();
};

export const useHomeStore = () => {
  const [lists, { refetch: refetchLists }] = createResource(fetchLists);
  const [slides, { refetch: refetchSlides }] = createResource<HomeLink[]>(getCarouselSlides);
  const loading = () => lists.loading || slides.loading;

  return {
    lists,
    slides,
    loading,
    refetch: () => {
      refetchLists();
      refetchSlides();
    }
  };
};